<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>服务部署管理</title>
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/element-plus/2.3.14/index.min.css">
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/3.3.4/vue.global.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/element-plus/2.3.14/index.full.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/element-plus-icons-vue/2.1.0/index.iife.min.js"></script>
    <script src="/lib/axios.min.js"></script>
</head>
<body>
    <div id="app">
        <el-container>
            <el-main>
                <el-card class="box-card">
                    <template #header>
                        <div class="card-header">
                            <h2>服务部署管理</h2>
                        </div>
                    </template>
                    <el-form :model="form" label-width="120px">
                        <el-form-item label="仓库UUID">
                            <el-input v-model="form.cangKuUuid" placeholder="请输入仓库UUID">
                                <template #append>
                                    <el-button @click="getServiceList">刷新列表</el-button>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-form>

                    <el-table :data="serviceList" style="width: 100%" v-loading="loading">
                        <el-table-column width="100" label="序号" type="index"></el-table-column>
                        <el-table-column prop="servicePackageName" label="服务包名称">
                        </el-table-column>
                        <el-table-column label="状态" >
                            <template #default="scope">
                                <el-tag :type="scope.row.serviceStatus === '1' ? 'success' : 'info'">
                                    {{ scope.row.serviceStatus === '1' ? '运行中' : '已停止' }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="200">
                            <template #default="scope">
                                <el-button-group>
                                    <el-button 
                                        type="primary" 
                                        :disabled="scope.row.serviceStatus === '1'"
                                        @click="handleDeploy(scope.row)">
                                        部署
                                    </el-button>
                                    <el-button 
                                        type="danger" 
                                        :disabled="scope.row.serviceStatus === '0'"
                                        @click="stopService(scope.row)">
                                        停止
                                    </el-button>
                                </el-button-group>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-card>
            </el-main>
        </el-container>

        <!-- 部署日志对话框 -->
        <el-dialog
            v-model="deployDialogVisible"
            title="部署日志"
            width="60%"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            :show-close="false">
            <div class="deployment-status" v-if="isDeploying">
                <el-progress type="circle" 
                    :percentage="deploymentProgress"
                    :status="deploymentProgress >= 100 ? 'success' : ''">
                    <template #default>
                        <span>{{ Math.floor(deploymentTimeLeft) }}秒</span>
                    </template>
                </el-progress>
            </div>
            <div class="log-window" ref="logWindow" style="
                background-color: #1e1e1e;
                color: #d4d4d4;
                font-family: monospace;
                padding: 10px;
                height: 400px;
                overflow-y: auto;
                white-space: pre-wrap;
                word-wrap: break-word;">
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" v-if="deploymentFinished" @click="closeDeployDialog">
                        确定
                    </el-button>
                    <el-button type="danger" v-if="isDeploying" @click="handleCancelDeployment">
                        取消部署
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>

    <script>
        const { createApp, ref } = Vue;
        const { ElMessage, ElMessageBox } = ElementPlus;

        const app = createApp({
            setup() {
                const form = ref({
                    cangKuUuid: ''
                });
                const loading = ref(false);
                // const serviceList = ref([]);
                const serviceList = ref([
                    {
                        "serviceStatus": "0",
                        "lastModified": "2025-07-10 14:51:24",
                        "servicePackageName": "flowableDemo-2025-07-10-14-34-49983.jar"
                    },
                    {
                        "serviceStatus": "0",
                        "lastModified": "2025-07-10 09:06:41",
                        "servicePackageName": "flowableDemo-2025-07-10-09-05-32813.jar"
                    },
                    {
                        "serviceStatus": "1",
                        "lastModified": "2025-07-10 09:50:04",
                        "servicePackageName": "flowableDemo-2025-07-10-09-49-39044.jar"
                    }
                ]);
                const deployDialogVisible = ref(false);
                const deploymentFinished = ref(false);
                const logWindow = ref(null);
                const isDeploying = ref(false);
                const deploymentProgress = ref(0);
                const deploymentTimeLeft = ref(180); // 3分钟倒计时
                let deploymentTimer = null;
                let deploymentController = null;

                const startDeploymentTimer = () => {
                    const startTime = Date.now();
                    const timeout = 180000; // 3分钟
                    
                    deploymentTimer = setInterval(() => {
                        const elapsed = Date.now() - startTime;
                        const remaining = timeout - elapsed;
                        
                        if (remaining <= 0) {
                            clearInterval(deploymentTimer);
                            deploymentTimeLeft.value = 0;
                            deploymentProgress.value = 100;
                            return;
                        }
                        
                        deploymentTimeLeft.value = remaining / 1000;
                        deploymentProgress.value = (elapsed / timeout) * 100;
                    }, 1000);
                };

                const handleCancelDeployment = async () => {
                    try {
                        await ElMessageBox.confirm(
                            '确定要取消部署吗？这可能会导致服务状态不稳定。',
                            '取消确认',
                            {
                                confirmButtonText: '确定',
                                cancelButtonText: '继续等待',
                                type: 'warning'
                            }
                        );
                        
                        if (deploymentController) {
                            deploymentController.abort();
                        }
                        clearInterval(deploymentTimer);
                        isDeploying.value = false;
                        deploymentFinished.value = true;
                        appendLog('error', '部署已被用户取消');
                    } catch (error) {
                        // 用户选择继续等待
                        if (error === 'cancel') {
                            return;
                        }
                    }
                };

                const closeDeployDialog = () => {
                    deployDialogVisible.value = false;
                    deploymentFinished.value = false;
                    isDeploying.value = false;
                    deploymentProgress.value = 0;
                    deploymentTimeLeft.value = 180;
                    if (deploymentTimer) {
                        clearInterval(deploymentTimer);
                    }
                    getServiceList();
                };

                const appendLog = (type, message) => {
                    console.log('添加日志:', type, message);
                    if (!logWindow.value) {
                        console.error('找不到日志窗口元素');
                        return;
                    }
                    const logLine = document.createElement('p');
                    logLine.style.margin = '0';
                    logLine.style.lineHeight = '1.5';
                    
                    switch(type.toLowerCase()) {
                        case 'info':
                            logLine.style.color = '#569cd6';
                            break;
                        case 'error':
                            logLine.style.color = '#f14c4c';
                            break;
                        case 'success':
                            logLine.style.color = '#6a9955';
                            break;
                        default:
                            logLine.style.color = '#d4d4d4';
                    }
                    
                    logLine.textContent = message;
                    logWindow.value.appendChild(logLine);
                    logWindow.value.scrollTop = logWindow.value.scrollHeight;
                };

                const deployService = async (service) => {
                    console.log('开始部署服务:', service);
                    
                    try {
                        deploymentController = new AbortController();
                        deploymentFinished.value = false;
                        deployDialogVisible.value = true;
                        isDeploying.value = true;
                        deploymentProgress.value = 0;
                        deploymentTimeLeft.value = 180;
                        
                        if (logWindow.value) {
                            logWindow.value.innerHTML = '';
                        }

                        const url = `/deployment/deploy?cangKuUuid=${encodeURIComponent(form.value.cangKuUuid)}&jarName=${encodeURIComponent(service.servicePackageName)}`;
                        console.log('请求URL:', url);

                        appendLog('info', '开始部署服务...');
                        startDeploymentTimer();
                        
                        const response = await fetch(url, {
                            signal: deploymentController.signal
                        });

                        console.log('收到响应:', response);

                        if (!response.ok) {
                            throw new Error(`HTTP error! status: ${response.status}`);
                        }

                        const reader = response.body.getReader();
                        const decoder = new TextDecoder();
                        let buffer = '';

                        while (true) {
                            const {value, done} = await reader.read();
                            if (done) {
                                console.log('流读取完成');
                                break;
                            }

                            const chunk = decoder.decode(value, {stream: true});
                            console.log('收到数据块:', chunk);
                            buffer += chunk;
                            const lines = buffer.split('\n\n');
                            buffer = lines.pop() || '';

                            for (const line of lines) {
                                console.log('处理行:', line);
                                if (line.startsWith('data: ')) {
                                    try {
                                        const data = JSON.parse(line.slice(6));
                                        appendLog(data.type, data.message);

                                        if (data.type === 'SUCCESS' || data.type === 'ERROR') {
                                            clearInterval(deploymentTimer);
                                            deploymentFinished.value = true;
                                            isDeploying.value = false;
                                            if (data.type === 'SUCCESS') {
                                                deploymentProgress.value = 100;
                                            }
                                        }
                                    } catch (error) {
                                        console.error('解析日志消息失败:', error, line);
                                    }
                                }
                            }
                        }
                    } catch (error) {
                        console.error('部署服务异常:', error);
                        if (error.name === 'AbortError') {
                            appendLog('error', '部署已被用户取消');
                        } else {
                            appendLog('error', '连接异常: ' + error.message);
                        }
                        deploymentFinished.value = true;
                        isDeploying.value = false;
                    } finally {
                        if (deploymentTimer) {
                            clearInterval(deploymentTimer);
                        }
                    }
                };

                const getServiceList = async () => {
                    if (!form.value.cangKuUuid) {
                        ElMessage.error('请输入仓库UUID');
                        return;
                    }

                    loading.value = true;
                    try {
                        const response = await axios.get('/deployment/list', {
                            params: {
                                cangKuUuid: form.value.cangKuUuid
                            }
                        });

                        console.log('获取服务列表响应:', response.data);

                        if (response.data.code === 200) {
                            serviceList.value = response.data.data || [];
                            if (serviceList.value.length === 0) {
                                ElMessage.warning('没有找到可部署的服务');
                            }
                        } else {
                            ElMessage.error(response.data.msg || '获取服务列表失败');
                        }
                    } catch (error) {
                        console.error('获取服务列表异常:', error);
                        ElMessage.error(error.response?.data?.msg || '获取服务列表失败');
                    } finally {
                        loading.value = false;
                    }
                };

                // 处理部署按钮点击
                const handleDeploy = async (service) => {
                    console.log('点击部署按钮:', service); // 调试日志
                    if (!form.value.cangKuUuid) {
                        ElMessage.error('请输入仓库UUID');
                        return;
                    }
                    await deployService(service);
                };

                const stopService = async (service) => {
                    if (!form.value.cangKuUuid) {
                        ElMessage.error('请输入仓库UUID');
                        return;
                    }

                    try {
                        // 确认对话框
                        await ElMessageBox.confirm(
                            `确定要停止服务 "${service.servicePackageName}" 吗？`,
                            '停止确认',
                            {
                                confirmButtonText: '确定',
                                cancelButtonText: '取消',
                                type: 'warning'
                            }
                        );

                        const response = await axios.get('/deployment/stop', {
                            params: {
                                cangKuUuid: form.value.cangKuUuid,
                                jarName: service.servicePackageName
                            }
                        });

                        console.log('停止服务响应:', response.data);

                        if (response.data.code === 200) {
                            ElMessage({
                                type: 'success',
                                message: '服务已成功停止！'
                            });
                            getServiceList(); // 刷新列表
                        } else {
                            ElMessage({
                                type: 'error',
                                message: response.data.msg || '停止服务失败'
                            });
                        }
                    } catch (error) {
                        if (error === 'cancel') {
                            return; // 用户取消操作
                        }
                        console.error('停止服务异常:', error);
                        ElMessage({
                            type: 'error',
                            message: error.response?.data?.msg || '停止服务失败'
                        });
                    }
                };

                return {
                    form,
                    loading,
                    serviceList,
                    deployDialogVisible,
                    deploymentFinished,
                    logWindow,
                    isDeploying,
                    deploymentProgress,
                    deploymentTimeLeft,
                    getServiceList,
                    handleDeploy,
                    stopService,
                    closeDeployDialog,
                    handleCancelDeployment
                };
            }
        });

        // 添加全局错误处理
        window.onerror = function(message, source, lineno, colno, error) {
            console.error('Global error:', {message, source, lineno, colno, error});
        };

        app.use(ElementPlus);
        app.mount('#app');
    </script>

    <style>
        .box-card {
            width: 800px;
            margin: 20px auto;
        }
        .card-header {
            text-align: center;
        }
        .el-main {
            padding: 20px;
        }
        .deployment-status {
            text-align: center;
            margin-bottom: 20px;
        }
    </style>
</body>
</html> 